﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using IBatisNet.DataMapper.Configuration;
using IBatisNet.DataMapper;

using VehicleManagement.Codes;
using VehicleManagement.Models;
using VehicleManagement.ControllersServices;
using System.Collections;
using System.IO;


namespace VehicleManagement.Controllers
{

    public class AdminInfoController : Controller
    {
        AdminServices adminServices = new AdminServices();

        //
        // GET: /AdminInfo/
        [CustomerAuthorize(Roles = "管理员")]
        public ActionResult Index()
        {
            if (Session["CompanyName"] != null && Session["CompanyName"].ToString().Equals("yuyu"))
            {
                if (Session["UserID"] == null)
                    Response.Redirect("/Home/Login");
                return View(adminServices.GetAllAdminInfo());
            }
            else
            {
                return RedirectToAction("../Home/Login");
            }
        }

        //
        // GET: /AdminInfo/Details/5

        [CustomerAuthorize(Roles = "管理员")]
        public ActionResult Details(int id)
        {
            if (Session["CompanyName"] != null && Session["CompanyName"].ToString().Equals("yuyu"))
            {
                if (Session["UserID"] == null)
                    Response.Redirect("/Home/Login");
                AdminInfo admin = adminServices.GetAdminInfo(id);
                return View(admin);
            }
            else
            {
                return RedirectToAction("../Home/Login");
            }
        }

        //
        // GET: /AdminInfo/MyInformation

        /// <summary>
        /// 获取管理员信息(如管理员个人中心)
        /// </summary>
        /// <param name="id">管理员ID</param>
        /// <returns></returns>
        [CustomerAuthorize(Roles = "管理员")]
        public ActionResult MyInformation()
        {
            if (Session["UserID"] == null)
                Response.Redirect("/Home/Login");
            int id = Convert.ToInt32(Session["UserID"]);
            return View(adminServices.GetAdminInfo(id));
        }

        [HttpPost, CustomerAuthorize(Roles = "管理员")]
        public ActionResult MyInformation(AdminInfo adminInfo)
        {
            if (ModelState.IsValid)
            {
                int rows = adminServices.EditAdminInfo(adminInfo);
                if (rows == 1)
                    RedirectToAction("MyInformation");
            }

            return View(adminInfo);

        }

        /// <summary>
        /// 管理员信息修改
        /// </summary>
        /// <param name="id">管理员ID</param>
        /// <param name="driveriofo">返回管理员类</param>
        /// <returns>修改管理员的视图</returns>
        [CustomerAuthorize(Roles = "管理员")]
        public ActionResult Edit(int id)
        {
            if (Session["CompanyName"] != null && Session["CompanyName"].ToString().Equals("yuyu"))
            {
                if (Session["UserID"] == null)
                    Response.Redirect("/Home/Login");
                AdminInfo adminInfo = adminServices.GetAdminInfo(id);
                return View(adminInfo);
            }
            else
            {
                return RedirectToAction("../Home/Login");
            }
        }

        [HttpPost, CustomerAuthorize(Roles = "管理员")]
        public ActionResult Edit(AdminInfo adminInfo)
        {
            if (ModelState.IsValid)
            {
                int rows = adminServices.EditAdminInfo(adminInfo);
                HttpPostedFileBase file = Request.Files["file"];
                if (file.ContentLength > 0)
                {
                    string fileExt = Path.GetExtension(file.FileName).ToLower();
                    int id = adminInfo.AdminID;
                    file.SaveAs(Server.MapPath("~/Photos/Admin") + @"\" + id + fileExt);
                    SqlMapperManager.Instance.Get().Update("UPDATE_ADMIN_HEAD_IMAGE",
                        new
                        {
                            AdminID = id,
                            Image = id + fileExt
                        });
                }
                if (rows == 1)
                    return RedirectToAction("Index");
            }

            return View(adminInfo);
        }

        [HttpPost, ActionName("DeleteAdmin"), CustomerAuthorize(Roles = "管理员")]
        public ActionResult DeleteConfirmed(int id)
        {
            if (Request.IsAjaxRequest())
            {
                int i = adminServices.DeleteAdmin(id);
                if (i > 0)
                {
                    return Json(new { Result = "true", Message = "删除成功" });
                }
                else
                {
                    return Json(new { Result = "false", Message = "删除失败" });
                }
            }
            else
            {
                return Json(new { Result = "false", Message = "该方法只能通过AJAX方式调用" });
            }
        }

        //
        // GET: /AdminInfo/Register
        /// <summary>
        /// 公司注册一个管理员的帐号
        /// </summary>
        /// <returns></returns>
        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /AdminInfo/Register
        [HttpPost]
        public ActionResult Register(AdminInfo adminInfo)
        {
            if (ModelState.IsValid)
            {
                object obj = adminServices.Register(adminInfo);
                return View("../Home/Login");
            }
            return View(adminInfo);
        }

        // POST: /AdminInfo/AdminRegister
        /// <summary>
        /// 使用AJAX申请一个管理员帐号
        /// </summary>
        /// <param name="loginName">登录帐号</param>
        /// <param name="companyName">公司名称</param>
        /// <param name="email">电子邮件</param>
        /// <param name="telephone">联系电话</param>
        /// <returns></returns>
        [HttpPost, ActionName("AdminRegister")]
        public ActionResult AdminRegister(string loginName, string companyName, string email, string telephone)
        {
            Hashtable ht = new Hashtable();
            ht.Add("loginName", loginName);
            ht.Add("companyName", companyName);
            ht.Add("email", email);
            ht.Add("telephone", telephone);
            if (Request.IsAjaxRequest())
            {
                int i = adminServices.AdminRegister(ht);
                if (i > 0)
                {
                    return Json(new { Result = "true", Message = "注册成功" });
                }
                else
                {
                    return Json(new { Result = "false", Message = "注册失败" });
                }
            }
            else
            {
                return Json(new { Result = "false", Message = "该方法只能通过AJAX方式调用" });
            }
        }


        /// <summary>
        /// 注册时，联系电话不能重复。
        /// </summary>
        /// <param name="telephone">联系电话</param>
        /// <returns>Json字符串提醒</returns>
        [HttpPost]
        public ActionResult CheckTelephone(string telephone)
        {
            IList<string> list = SqlMapperManager.Instance.Get().QueryForList<string>("SELECT_Admin_Telephone", null);
            bool exists = string.IsNullOrEmpty(list.FirstOrDefault(u => u.ToLower() == telephone.ToLower())) == false;
            if (exists)
            {
                return Json(new { Result = "false", Message = "联系电话已被注册" });

            }
            else
            {
                return Json(new { Result = "true", Message = "联系电话可以使用" });
            }


        }

        /// <summary>
        /// 注册时，电子邮件不能重复。
        /// </summary>
        /// <param name="loginName">电子邮件</param>
        /// <returns>Json字符串提醒</returns>
        [HttpPost]
        public ActionResult CheckEmail(string email)
        {
            IList<string> list = SqlMapperManager.Instance.Get().QueryForList<string>("SELECT_Admin_Email", null);
            bool exists = string.IsNullOrEmpty(list.FirstOrDefault(u => u.ToLower() == email.ToLower())) == false;
            if (exists)
            {
                return Json(new { Result = "false", Message = "电子邮件已被注册" });

            }
            else
            {
                return Json(new { Result = "true", Message = "电子邮件可以使用" });
            }


        }

        /// <summary>
        /// 注册时，公司名称不能重复。
        /// </summary>
        /// <param name="companyName">公司名称</param>
        /// <returns>Json字符串提醒</returns>
        [HttpPost]
        public ActionResult CheckCompanyName(string companyName)
        {
            IList<string> list = SqlMapperManager.Instance.Get().QueryForList<string>("SELECT_Admin_CompanyName", null);
            bool exists = string.IsNullOrEmpty(list.FirstOrDefault(u => u.ToLower() == companyName.ToLower())) == false;
            if (exists)
            {
                return Json(new { Result = "false", Message = "公司名称已被注册" });

            }
            else
            {
                return Json(new { Result = "true", Message = "公司名称可以使用" });
            }


        }

        /// <summary>
        /// 注册时，公司名称不能重复。
        /// </summary>
        /// <param name="loginName">登录帐号</param>
        /// <returns>Json字符串提醒</returns>
        [HttpPost]
        public ActionResult CheckLoginName(string loginName)
        {
            IList<string> list = SqlMapperManager.Instance.Get().QueryForList<string>("SELECT_Admin_LoginName", null);
            bool exists = string.IsNullOrEmpty(list.FirstOrDefault(u => u.ToLower() == loginName.ToLower())) == false;
            if (exists)
            {
                return Json(new { Result = "false", Message = "登录帐号已被注册" });

            }
            else
            {
                return Json(new { Result = "true", Message = "登录帐号可以使用" });
            }


        }
    }
}
